# FILE: WikiLinkBroker.py
# DESC: obtains wiki url corresponding to GeoName object 
#

# TODO: move to oreus.conf, context geonames


WIKI_LINK_SEARCH_URL="http://ws.geonames.org/findNearbyWikipediaJSON?lat=%s&lng=%s&country=%s&maxRows=%d&radius=%d&lang=%s"

from web.service.WebServiceBroker import WebServiceBroker
from infra.logging import logger

class WikiLinkBroker(WebServiceBroker):

	def setWikiLink(self, geoName, maxRows = 500, radius = 30, lang = "en"):
		log = logger.getLogger()
		wikiLinkMatched = False
		response = self.requestJSON(WIKI_LINK_SEARCH_URL % (geoName.getLatitude(), geoName.getLongitude(), geoName.getCountryCode(), maxRows, radius, lang))
		try:
			if response and response.has_key("geonames") and response["geonames"]:
				for wikiLink in response["geonames"]:
					if geoName.getFeature().equals(wikiLink["feature"]):
						geoName.setWikiUrl(wikiLink["wikipediaUrl"])
						geoName.setWikiImage(wikiLink["thumbnailImg"])
						wikiLinkMatched = True
						break
			
			if not wikiLinkMatched:
				log.debug("Did not find any wiki in radius = %d km of geoName = \"%s\ (feature = \"%s\"), written in lang = \"%s\"." \
						% (radius, geoName.getName(), geoName.getFeature().getName(), lang) )
				geoName.setWikiUrl(None)
		except KeyError:
			pass
